const http = require('http');
const path = require('path');
const url = require('url');
const multiparty = require('multiparty');
const fse = require('fs-extra');
const mergeFileChunk = require('./mergeFile.js');

const server = http.createServer();
const UPLOAD_DIR = path.resolve(__dirname, '.', 'target');
let step = 0;

// 定义一个休眠方法
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

server.on('request', async (req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Header', '*');

  // 优化
  if (req.method === 'OPTIONS') {
    res.status = 200;
    res.end();
    return;
  }

  // 合并文件
  const urlObj = url.parse(req.url, true);
  // console.log(22, urlObj);
  if (urlObj.pathname === '/merge') {
    // 引入合并文件的方法，抽离到外部文件
    const perSize = urlObj.query.perSize;
    const fileName = urlObj.query.filename;
    const filePath = path.resolve(UPLOAD_DIR, '.', fileName);
    await mergeFileChunk(res, fileName.split('.')[0], filePath, perSize);
    return;
  }

  if (req.url === '/') {
    step++;
    const myMultiparty = new multiparty.Form();
    myMultiparty.parse(req, async (err, fields, files) => {
      if (err) return;
      const [fileName] = fields.fileName;
      const [chunk] = files.chunk;

      const slice_dir_name = fileName.split('-')[0];
      const chunkDirPath = path.resolve(UPLOAD_DIR, '.', slice_dir_name);

      if (!fse.existsSync(chunkDirPath)) {
        await fse.mkdirs(chunkDirPath);
      }

      await fse.move(chunk.path, `${chunkDirPath}/${fileName}`, { overwrite: true });
      // await sleep(1000 * fileName.split('-')[1]);
      console.log(1000 * fileName.split('-')[1]);
      res.end('/ ok');
      return;
    });
  }
});

server.listen(3000);
